package cc.rengu.redp.bizimpl.igas.service.impl;

import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.dao.PSrcChannelInfoMapper;
import cc.rengu.redp.bizimpl.igas.domain.PSrcChannelInfo;
import cc.rengu.redp.bizimpl.igas.domain.PSrcTxnAuthCfg;
import cc.rengu.redp.bizimpl.igas.domain.PTxnCfg;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.igas.service.PSrcChannelInfoService;
import cc.rengu.redp.bizimpl.igas.service.PSrcTxnAuthCfgService;
import cc.rengu.redp.bizimpl.igas.service.PTxnCfgService;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-08
 */
@DS("igas")
@Service
public class PSrcChannelInfoServiceImpl extends ServiceImpl<PSrcChannelInfoMapper, PSrcChannelInfo> implements PSrcChannelInfoService {
    @Autowired
    private IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;
    @Autowired
    private PSrcTxnAuthCfgService pSrcTxnAuthCfgService;
    @Autowired
    private PTxnCfgService pTxnCfgService;
    @Autowired
    IUpmpSysParamService upmpSysParamService;
    private String oprMenuId = "20000015";
    private String oprMenuName = "产品管理:交易渠道管理";
    private String oprBtnNamePrefix = "交易渠道管理";
    private String webNextUrl = "/admin/igas/pSrcChannelInfo/edit";
    @Override
    public IPage<PSrcChannelInfo> findByPage(QueryRequest request, PSrcChannelInfo info) {
        try {
            LambdaQueryWrapper<PSrcChannelInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.eq(PSrcChannelInfo::getInstId, info.getInstId());
            } else {
                //获取当前用户的法人id
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                queryWrapper.eq(PSrcChannelInfo::getInstId, user.getInstId());
            }
            if (StringUtils.isNotBlank(info.getSrcChannelId())) {
                queryWrapper.likeRight(PSrcChannelInfo::getSrcChannelId, info.getSrcChannelId());
            }
            if (StringUtils.isNotBlank(info.getSrcChannelName())) {
                queryWrapper.likeRight(PSrcChannelInfo::getSrcChannelName, info.getSrcChannelName());
            }
            queryWrapper.orderByDesc(PSrcChannelInfo::getSrcChannelId);
            Page<PSrcChannelInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }
    @Override
    @Transactional
    public void update(PSrcChannelInfo entity) throws RedpException {
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        entity.setUpdateTime(lastUpddt);
        LambdaQueryWrapper<PSrcChannelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PSrcChannelInfo::getInstId, entity.getInstId());
        wrapper.eq(PSrcChannelInfo::getSrcChannelId, entity.getSrcChannelId());
        if(PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(entity.getOptFlag())){

            //         UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(),oprBtnNamePrefix+ BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_ADD.getDesc());
            //            if(null!=privilegeCheck&&BusinessContainer.YES.equals(privilegeCheck.getChecked())){
//            log.error("不支持审核操作!");
//            throw new RedpException("不支持审核操作！");
//        } else {
            // 获取当前登录用户信息
            // 新增
            entity.setTransChannelStatus(IgasYesOrNoEnum.Yes.getType());
            entity.setCreateTime(lastUpddt);
            if(StringUtils.isNotBlank(entity.getSupportAcctType())){
                entity.setSupportAcctType(pDstChannelInfoService.getSupportAcctType(entity.getSupportAcctType()));
            }
            this.baseMapper.insert(entity);
            // 处理交易配置
            List<String> selectedTxnList = new ArrayList<>();
            if (entity.getSurportTxnList()!=null){
                selectedTxnList= entity.getSurportTxnList();
            }
            // 先删除
            pSrcTxnAuthCfgService.deletePSrcTxnAuthCfg(entity.getInstId(), entity.getSrcChannelId(), entity.getTransChannelId());
            // 再新增
            List<PTxnCfg> allTxnList = pTxnCfgService.findPTxnCfgByList(null, null, null, null);
            Map<String, PTxnCfg> allTxnMap = Maps.newHashMap();
            for (PTxnCfg pTxnCfg : allTxnList) {
                allTxnMap.put(pTxnCfg.getTxnNum(), pTxnCfg);
            }
            // 将页面已选的入库
            for (String txnNum : selectedTxnList) {
                if(!allTxnMap.containsKey(txnNum)){
                    continue;
                }
                PTxnCfg pTxnCfg = allTxnMap.get(txnNum);
                // 组装数据
                PSrcTxnAuthCfg pSrcTxnAuthCfg=new PSrcTxnAuthCfg();
                pSrcTxnAuthCfg.setInstId(entity.getInstId());
                pSrcTxnAuthCfg.setMsgSrcId(entity.getSrcChannelId());
                pSrcTxnAuthCfg.setTransChannelId(entity.getTransChannelId());
                pSrcTxnAuthCfg.setTxnNum(txnNum);

                pSrcTxnAuthCfg.setBizType(pTxnCfg.getBizType());
                pSrcTxnAuthCfg.setTxnGroup(pTxnCfg.getTxnGroup());
                pSrcTxnAuthCfg.setBizProdCode(pTxnCfg.getBizProdCode());
                pSrcTxnAuthCfg.setServiceName(pTxnCfg.getServiceName());
                pSrcTxnAuthCfg.setTxnTimeout(pTxnCfg.getTxnTimeout());
                pSrcTxnAuthCfg.setSupportFlag(pTxnCfg.getSupportFlag());
                pSrcTxnAuthCfg.setSupportBeginTime(pTxnCfg.getSupportBeginTime());
                pSrcTxnAuthCfg.setSupportEndTime(pTxnCfg.getSupportEndTime());
                pSrcTxnAuthCfg.setSupportAcctType(entity.getSupportAcctType());
                // pSrcTxnAuthCfg.setMaxSupportNum();
                // pSrcTxnAuthCfg.setRelateOrigTxnFlag();
                pSrcTxnAuthCfg.setTxnRegisterFlag(pTxnCfg.getTxnRegisterFlag());
                pSrcTxnAuthCfg.setMsgRegisterFlag(pTxnCfg.getMsgRegisterFlag());
                pSrcTxnAuthCfg.setSignFlag(pTxnCfg.getSignFlag());
                pSrcTxnAuthCfg.setPinFlag(pTxnCfg.getPinFlag());
                pSrcTxnAuthCfg.setTxnName(pTxnCfg.getTxnName());
                pSrcTxnAuthCfg.setCreateTime(pTxnCfg.getCreateTime());
                pSrcTxnAuthCfg.setUpdateTime(pTxnCfg.getUpdateTime());
                pSrcTxnAuthCfgService.insertPSrcTxnAuthCfg(pSrcTxnAuthCfg);
            }

//        }
        }if(PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(entity.getOptFlag())){

            //         UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(),oprBtnNamePrefix+ BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_ADD.getDesc());
            //            if(null!=privilegeCheck&&BusinessContainer.YES.equals(privilegeCheck.getChecked())){
//            log.error("不支持审核操作!");
//            throw new RedpException("不支持审核操作！");
//        } else {
            // 修改
            PSrcChannelInfo pSrcChannelInfo = this.getOne(wrapper);
            if(StringUtils.isNotBlank(entity.getSupportAcctType())){
                entity.setSupportAcctType(pDstChannelInfoService.getSupportAcctType(entity.getSupportAcctType()));
            }
            BeanUtils.copyProperties(entity, pSrcChannelInfo);
            this.baseMapper.update(pSrcChannelInfo, wrapper);

            // 处理交易配置
            List<String> selectedTxnList = pSrcChannelInfo.getSurportTxnList();
            // 先删除
            pSrcTxnAuthCfgService.deletePSrcTxnAuthCfg(pSrcChannelInfo.getInstId(), pSrcChannelInfo.getSrcChannelId(), pSrcChannelInfo.getTransChannelId());
            // 再新增
            List<PTxnCfg> allTxnList = pTxnCfgService.findPTxnCfgByList(null, null, null, null);
            Map<String, PTxnCfg> allTxnMap = Maps.newHashMap();
            for (PTxnCfg pTxnCfg : allTxnList) {
                allTxnMap.put(pTxnCfg.getTxnNum(), pTxnCfg);
            }
            // 将页面已选的入库
            if (null != selectedTxnList) {
                for (String txnNum : selectedTxnList) {
                    if (!allTxnMap.containsKey(txnNum)) {
                        continue;
                    }
                    PTxnCfg pTxnCfg = allTxnMap.get(txnNum);
                    // 组装数据
                    PSrcTxnAuthCfg pSrcTxnAuthCfg = new PSrcTxnAuthCfg();
                    pSrcTxnAuthCfg.setInstId(pSrcChannelInfo.getInstId());
                    pSrcTxnAuthCfg.setMsgSrcId(pSrcChannelInfo.getSrcChannelId());
                    pSrcTxnAuthCfg.setTransChannelId(pSrcChannelInfo.getTransChannelId());
                    pSrcTxnAuthCfg.setTxnNum(txnNum);

                    pSrcTxnAuthCfg.setBizType(pTxnCfg.getBizType());
                    pSrcTxnAuthCfg.setTxnGroup(pTxnCfg.getTxnGroup());
                    pSrcTxnAuthCfg.setBizProdCode(pTxnCfg.getBizProdCode());
                    pSrcTxnAuthCfg.setServiceName(pTxnCfg.getServiceName());
                    pSrcTxnAuthCfg.setTxnTimeout(pTxnCfg.getTxnTimeout());
                    pSrcTxnAuthCfg.setSupportFlag(pTxnCfg.getSupportFlag());
                    pSrcTxnAuthCfg.setSupportBeginTime(pTxnCfg.getSupportBeginTime());
                    pSrcTxnAuthCfg.setSupportEndTime(pTxnCfg.getSupportEndTime());
                    pSrcTxnAuthCfg.setSupportAcctType(pSrcChannelInfo.getSupportAcctType());
                    // pSrcTxnAuthCfg.setMaxSupportNum();
                    // pSrcTxnAuthCfg.setRelateOrigTxnFlag();
                    pSrcTxnAuthCfg.setTxnRegisterFlag(pTxnCfg.getTxnRegisterFlag());
                    pSrcTxnAuthCfg.setMsgRegisterFlag(pTxnCfg.getMsgRegisterFlag());
                    pSrcTxnAuthCfg.setSignFlag(pTxnCfg.getSignFlag());
                    pSrcTxnAuthCfg.setPinFlag(pTxnCfg.getPinFlag());
                    pSrcTxnAuthCfg.setTxnName(pTxnCfg.getTxnName());
                    pSrcTxnAuthCfg.setCreateTime(pTxnCfg.getCreateTime());
                    pSrcTxnAuthCfg.setUpdateTime(pTxnCfg.getUpdateTime());
                    pSrcTxnAuthCfgService.insertPSrcTxnAuthCfg(pSrcTxnAuthCfg);
                }
            }
//        }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(entity.getOptFlag())
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(entity.getOptFlag())
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(entity.getOptFlag())) {
            UpmpPrivilegeCheck privilegeCheck;
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(entity.getOptFlag())) {
             /*   privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix + BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_STOP.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                entity.setTransChannelStatus(IgasYesOrNoEnum.No.getType());
                /* }*/
            }else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(entity.getOptFlag())) {
              /*  privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix+ BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_USE.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                entity.setTransChannelStatus(IgasYesOrNoEnum.Yes.getType());
                /* }*/
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(entity.getOptFlag())) {
                /*privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix+ BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_CANCEL.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                entity.setTransChannelStatus(IgasYesOrNoEnum.No.getType());
                /* }*/
            }
            this.baseMapper.update(entity, wrapper);
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(entity.getOptFlag())) {
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        }
    }

    @Override
    public void updateStatus(PSrcChannelInfo entity) throws RedpException {
        try {
            if (entity.getTransChannelStatus().equals("Y")){
                entity.setTransChannelStatus("N");
            }else {
                entity.setTransChannelStatus("Y");
            }
            LambdaQueryWrapper<PSrcChannelInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PSrcChannelInfo::getInstId, entity.getInstId());
            wrapper.eq(PSrcChannelInfo::getSrcChannelId, entity.getSrcChannelId());
            this.baseMapper.update(entity, wrapper);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }
}
